package cn.netjava.dao;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import cn.netjava.dbutil.Conn2DB;
import cn.netjava.pojo.ReplayMsg;

public class ReplayMsgDao {
    public static ReplayMsgDao rmdao;
 	
	/*make ReplayMsgDao pravate*/
	private ReplayMsgDao(){}
	
	/*obtain a ReplayMsgDao object*/
	public static ReplayMsgDao getReplayMsgDao(){
		if(null==rmdao){
			rmdao = new ReplayMsgDao();
		}
		return rmdao;
	}
	
	/**
	 * to add a replay message which response the user whose id is the userID
	 * @param replayMsgContent
	 * @param userID
	 * @param msgID
	 * @return
	 */
	public boolean addReplayMsg(String replayMsgContent,int userID,int msgID){
		String sql="insert into tbl_replaymsgs(replaymsgcontent,ins_id,ins_msgid,ins_dt)values(?,?,?,?)";
		try{
			java.sql.Connection conn =Conn2DB.getConn();
			java.sql.PreparedStatement pstmt =conn.prepareStatement(sql);
			
			pstmt.setString(1, replayMsgContent);
			pstmt.setInt(2, userID);
			pstmt.setInt(3, msgID);
			/*obtain the system time*/
			java.sql.Timestamp timeStamp =new java.sql.Timestamp(System.currentTimeMillis());
			String ins_td =timeStamp.toString().substring(0,timeStamp.toString().lastIndexOf("."));
			pstmt.setString(4, ins_td); 
			
			pstmt.executeUpdate();			
			pstmt.close();						
			return true;
		}catch(Exception ef){
			ef.printStackTrace();
		}
		return false;
	}
	
	/**
	 * to get message's replay message
	 * @param msgID
	 * @return
	 */
	public List<ReplayMsg> getReplayMsgFromMsgID(int msgID){
		List<ReplayMsg> replayMsgList =new ArrayList<ReplayMsg>();
		String sql="select *from tbl_replaymsgs where ins_msgid=?";
		try{
			java.sql.Connection conn =Conn2DB.getConn();
			java.sql.PreparedStatement pstmt =conn.prepareStatement(sql);
			pstmt.setInt(1, msgID);
			
			ResultSet rs =pstmt.executeQuery();
			while(rs.next()){
				ReplayMsg replayMsg =new ReplayMsg();
				
				replayMsg.setId(rs.getInt("id"));
				replayMsg.setReplayMsgContent(rs.getString(""));
				replayMsg.setUser(UserDao.getUserDao().getUserFromID(rs.getInt("ins_id")));
				replayMsg.setMsg(MsgDao.getMsgDao().getMsgFromMsgID(rs.getInt("ins_msgid")));
				replayMsg.setIns_dt(rs.getString("ins_dt"));
				
				replayMsgList.add(replayMsg);
			}
			pstmt.executeUpdate();			
			pstmt.close();						
		}catch(Exception ef){
			ef.printStackTrace();
		}	
		return replayMsgList;
	}
}
